<script setup>
import { ref, reactive, computed } from 'vue'

const emit = defineEmits(['search', 'cancel'])

// 搜索条件
const searchConditions = ref([
  {
    field: 'username',
    operator: 'contains',
    value: ''
  }
])

// 字段选项
const fieldOptions = [
  { value: 'username', label: '用户名' },
  { value: 'real_name', label: '姓名' },
  { value: 'email', label: '邮箱' },
  { value: 'phone', label: '手机号' },
  { value: 'status', label: '状态' },
  { value: 'last_login_time', label: '最后登录时间' },
  { value: 'created_at', label: '创建时间' }
]

// 操作符选项
const operatorOptions = [
  { value: 'equals', label: '等于' },
  { value: 'contains', label: '包含' },
  { value: 'startsWith', label: '开头是' },
  { value: 'endsWith', label: '结尾是' },
  { value: 'greaterThan', label: '大于' },
  { value: 'lessThan', label: '小于' },
  { value: 'between', label: '介于' }
]

// 状态值选项
const statusOptions = [
  { value: '1', label: '正常' },
  { value: '0', label: '禁用' }
]

// 逻辑选择
const logic = ref('AND')
const logicOptions = [
  { value: 'AND', label: '满足所有条件' },
  { value: 'OR', label: '满足任一条件' }
]

// 排序设置
const sortField = ref('created_at')
const sortDirection = ref('desc')

// 排序字段选项
const sortFieldOptions = [
  { value: 'username', label: '用户名' },
  { value: 'real_name', label: '姓名' },
  { value: 'last_login_time', label: '最后登录时间' },
  { value: 'created_at', label: '创建时间' }
]

// 排序方向选项
const sortDirectionOptions = [
  { value: 'asc', label: '升序' },
  { value: 'desc', label: '降序' }
]

// 是否显示状态值选择器
const showStatusSelect = (condition) => {
  return condition.field === 'status'
}

// 是否显示日期值选择器
const showDatePicker = (condition) => {
  return ['last_login_time', 'created_at'].includes(condition.field)
}

// 是否显示日期范围选择器
const showDateRangePicker = (condition) => {
  return ['last_login_time', 'created_at'].includes(condition.field) && condition.operator === 'between'
}

// 添加条件
const addCondition = () => {
  searchConditions.value.push({
    field: 'username',
    operator: 'contains',
    value: ''
  })
}

// 移除条件
const removeCondition = (index) => {
  if (searchConditions.value.length > 1) {
    searchConditions.value.splice(index, 1)
  }
}

// 提交搜索
const handleSearch = () => {
  // 过滤掉值为空的条件
  const validConditions = searchConditions.value.filter(condition => {
    if (Array.isArray(condition.value)) {
      return condition.value.length > 0
    }
    return condition.value !== undefined && condition.value !== ''
  })
  
  // 如果没有有效条件，不执行搜索
  if (validConditions.length === 0) {
    return
  }
  
  // 构建搜索参数
  const searchParams = {
    conditions: validConditions,
    logic: logic.value,
    sort: {
      field: sortField.value,
      direction: sortDirection.value
    }
  }
  
  emit('search', searchParams)
}

// 重置搜索
const resetSearch = () => {
  searchConditions.value = [
    {
      field: 'username',
      operator: 'contains',
      value: ''
    }
  ]
  logic.value = 'AND'
  sortField.value = 'created_at'
  sortDirection.value = 'desc'
}

// 取消搜索
const cancelSearch = () => {
  emit('cancel')
}

// 监听操作符变化，如果是 between，则初始化值为数组
const handleOperatorChange = (condition) => {
  if (condition.operator === 'between') {
    if (!Array.isArray(condition.value)) {
      condition.value = ['', '']
    }
  } else {
    // 如果从 between 切换到其他操作符，重置值
    if (Array.isArray(condition.value)) {
      condition.value = ''
    }
  }
}
</script>

<template>
  <div class="advanced-search-form">
    <h3 class="advanced-search-title">高级搜索</h3>
    
    <div class="search-conditions">
      <div v-for="(condition, index) in searchConditions" :key="index" class="condition-item">
        <div class="condition-field">
          <el-select v-model="condition.field" class="field-select">
            <el-option
              v-for="option in fieldOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </div>
        
        <div class="condition-operator">
          <el-select 
            v-model="condition.operator" 
            class="operator-select"
            @change="() => handleOperatorChange(condition)"
          >
            <el-option
              v-for="option in operatorOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </div>
        
        <div class="condition-value">
          <!-- 状态选择器 -->
          <el-select
            v-if="showStatusSelect(condition)"
            v-model="condition.value"
            class="value-input"
            placeholder="请选择状态"
          >
            <el-option
              v-for="option in statusOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
          
          <!-- 日期选择器 -->
          <el-date-picker
            v-else-if="showDatePicker(condition) && condition.operator !== 'between'"
            v-model="condition.value"
            type="datetime"
            placeholder="选择日期时间"
            class="value-input"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
          
          <!-- 日期范围选择器 -->
          <el-date-picker
            v-else-if="showDateRangePicker(condition)"
            v-model="condition.value"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            class="value-input"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
          
          <!-- 默认文本输入 -->
          <el-input
            v-else
            v-model="condition.value"
            placeholder="请输入值"
            class="value-input"
          />
        </div>
        
        <div class="condition-actions">
          <el-button 
            v-if="searchConditions.length > 1" 
            type="danger" 
            icon="Delete" 
            circle 
            @click="removeCondition(index)"
          />
        </div>
      </div>
      
      <div class="add-condition">
        <el-button type="primary" plain icon="Plus" @click="addCondition">
          添加条件
        </el-button>
      </div>
    </div>
    
    <div class="search-logic">
      <div class="logic-select">
        <span class="logic-label">条件关系:</span>
        <el-radio-group v-model="logic">
          <el-radio
            v-for="option in logicOptions"
            :key="option.value"
            :label="option.value"
          >
            {{ option.label }}
          </el-radio>
        </el-radio-group>
      </div>
      
      <div class="sort-select">
        <span class="sort-label">排序:</span>
        <el-select v-model="sortField" class="sort-field-select">
          <el-option
            v-for="option in sortFieldOptions"
            :key="option.value"
            :label="option.label"
            :value="option.value"
          />
        </el-select>
        
        <el-select v-model="sortDirection" class="sort-direction-select">
          <el-option
            v-for="option in sortDirectionOptions"
            :key="option.value"
            :label="option.label"
            :value="option.value"
          />
        </el-select>
      </div>
    </div>
    
    <div class="search-actions">
      <el-button @click="cancelSearch">取消</el-button>
      <el-button @click="resetSearch">重置</el-button>
      <el-button type="primary" @click="handleSearch">搜索</el-button>
    </div>
  </div>
</template>

<style scoped>
.advanced-search-form {
  background-color: var(--el-bg-color);
  border-radius: 4px;
  padding: 20px;
  margin-bottom: 20px;
}

.advanced-search-title {
  margin-top: 0;
  margin-bottom: 20px;
  color: var(--el-text-color-primary);
  font-size: 18px;
}

.search-conditions {
  margin-bottom: 20px;
}

.condition-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  gap: 12px;
}

.condition-field {
  width: 120px;
}

.condition-operator {
  width: 120px;
}

.condition-value {
  flex: 1;
}

.value-input {
  width: 100%;
}

.add-condition {
  margin-top: 16px;
}

.search-logic {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 12px;
}

.logic-select, .sort-select {
  display: flex;
  align-items: center;
  gap: 8px;
}

.logic-label, .sort-label {
  color: var(--el-text-color-secondary);
  white-space: nowrap;
}

.sort-field-select {
  width: 120px;
  margin-right: 8px;
}

.sort-direction-select {
  width: 80px;
}

.search-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

@media (max-width: 768px) {
  .condition-item {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .condition-field, .condition-operator, .condition-value {
    width: 100%;
    margin-bottom: 8px;
  }
  
  .search-logic {
    flex-direction: column;
    align-items: flex-start;
  }
}
</style> 